<template>
  <div class="container">
    <el-form ref="ruleForm" :model="query" :rules="rules" label-width="120px">
      <el-form-item label="任务标题" prop="taskTitle">
        <el-input
          v-model="query.taskTitle"
          placeholder="请输入任务标题"
        ></el-input>
      </el-form-item>
      <el-form-item label="单位业态" prop="bodyIndustry">
        <div class="checkbox">
          <el-checkbox
            class="checkbox_last"
            v-model="bodyIndustryAll"
            label="全选"
            name="type"
            @change="onCheckboxBodyIndustry"
          ></el-checkbox>
          <el-checkbox-group
            v-model="query.bodyIndustry"
            @change="onCheckboxGroupBodyIndustry"
          >
            <el-checkbox
              :label="item.bodyIndustryRemarks"
              name="type"
              v-for="item in query.bodyIndustryList"
              :key="item.id"
            ></el-checkbox>
          </el-checkbox-group>
        </div>
      </el-form-item>
      <el-form-item label="区域" prop="area">
        <div class="checkbox">
          <el-checkbox
            class="checkbox_last"
            v-model="areaAll"
            label="全选"
            name="type"
            @change="onCheckbox"
          ></el-checkbox>
          <el-checkbox-group v-model="query.area" @change="onCheckboxGroup">
            <el-checkbox
              :label="item.areaName"
              name="type"
              v-for="item in query.areaList"
              :key="item.areaCode"
            ></el-checkbox>
          </el-checkbox-group>
        </div>
      </el-form-item>
      <el-form-item label="完成截止时间" prop="completionDeadline">
        <el-date-picker
          v-model="query.completionDeadline"
          type="date"
          placeholder="选择日期"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="处理地址">
        <el-input
          placeholder="请输入处理地址"
          v-model="query.processingAddress"
        >
          <template slot="prepend">Http://</template>
        </el-input>
      </el-form-item>
      <el-form-item label="任务内容" prop="taskContent">
        <quill-editor
          :content="query.taskContent"
          :options="editorOption"
          @change="onEditorChange($event)"
        />
      </el-form-item>
      <el-form-item label="相关附件">
        <el-upload
          :file-list="query.unitModuleTaskFileSaveRequestList"
          drag
          :action="$upload"
            :headers="$headers()"
          :on-preview="
            e => {
              $downloadFiles(e.fileUrl);
            }
          "
          :on-error="onError"
          :on-remove="onRemove"
          :before-remove="beforeRemove"
          multiple
          :on-success="success"
          :before-upload="
            e => {
              return $beforeAvatarUpload(e, 1);
            }
          "
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">
            只能上传world、excel、pdf文件，且不超过5M
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="">
        <div class="form_button">
          <el-button type="primary" @click="submit(0)">仅保存</el-button>
          <el-button type="primary" @click="submit(1)">保存并下发</el-button>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { quillRedefine } from 'vue-quill-editor-upload';
export default {
  created() {
    this.findListNoParentByParentCode();
    this.getModulesCate();
    let data = JSON.parse(sessionStorage.getItem('viewTask'));
    if (data) {
      this.query.bodyIndustryList = data.unitModuleTaskFormatResponseList;
      this.query.areaList = data.unitModuleTaskAreaResponseList;
      this.query.completionDeadline = data.completionDeadlineStr;
      this.query.createUnitId = data.createUnitId;
      this.query.createUnitName = data.createUnitName;
      this.query.id = data.id;
      this.query.releaseStatus = data.releaseStatus;
      this.query.processingAddress = data.processingAddress;
      this.query.releaseTime = data.releaseTime;
      this.query.taskSource = data.taskSource;
      this.query.taskContent = data.taskContent;
      this.query.taskTitle = data.taskTitle;
      this.query.area = data.unitModuleTaskAreaResponseList.map(
        x => x.areaName
      );
      this.query.bodyIndustry = data.unitModuleTaskFormatResponseList.map(
        x => x.bodyIndustryAndBodyIndustryRemarks
      );
      data.unitModuleTaskFileResponseList.forEach(x => {
        x.name = x.fileName;
      });
      this.query.unitModuleTaskFileSaveRequestList =
        data.unitModuleTaskFileResponseList;
    }
    let that = this;
    this.editorOption = quillRedefine({
      // 图片上传的设置
      uploadConfig: {
        action: that.$upload, // 必填参数 图片上传地址
        // 必选参数  res是一个函数，函数接收的response为上传成功时服务器返回的数据
        // 你必须把返回的数据中所包含的图片地址 return 回去
        res: respnse => {
          if (respnse.code == 200) {
            return that.$uploadURL + respnse.data;
          } else {
            that.$error('上传失败');
          }
        },
        methods: 'POST', // 可选参数 图片上传方式  默认为post
        token: '', // 可选参数 如果需要token验证，假设你的token有存放在sessionStorage
        name: 'file', // 可选参数 文件的参数名 默认为img
        size: 5 * 1024, // 可选参数   图片限制大小，单位为Kb, 1M = 1024Kb
        accept: 'image/png,  image/jpeg, ', // 可选参数 可上传的图片格式
        // start: function (){}
        start: e => {}, // 可选参数 接收一个函数 开始上传数据时会触发
        end: e => {}, // 可选参数 接收一个函数 上传数据完成（成功或者失败）时会触发
        success: e => {}, // 可选参数 接收一个函数 上传数据成功时会触发
        error: () => {}, // 可选参数 接收一个函数 上传数据中断时会触发
      },
      // 以下所有设置都和vue-quill-editor本身所对应
      placeholder: '请输入编辑文章内容', // 可选参数 富文本框内的提示语
      theme: '', // 可选参数 富文本编辑器的风格
      toolOptions: [
        ['bold', 'italic', 'underline', 'strike'],
        ['blockquote', 'code-block'],
        [{ header: 1 }, { header: 2 }],
        [{ list: 'ordered' }, { list: 'bullet' }],
        [{ script: 'sub' }, { script: 'super' }],
        [{ indent: '-1' }, { indent: '+1' }],
        [{ direction: 'rtl' }],
        [{ size: ['small', false, 'large', 'huge'] }],
        [{ header: [1, 2, 3, 4, 5, 6, false] }],
        [{ color: [] }, { background: [] }],
        [{ font: [] }],
        [{ align: [] }],
        ['clean'],
        ['link', 'image'],
      ], // 可选参数  选择工具栏的需要哪些功能  默认是全部
      handlers: {},
    });
  },
  data() {
    return {
      form: {
        name: '',
        type: [],
      },
      content: '',
      editorOption: {},
      query: {
        completionDeadline: '',
        createUnitId: '12515115144224',
        createUnitName: '苏州亿通',
        id: '',
        processingAddress: '',
        releaseStatus: 0,
        releaseTime: '',
        remark: '',
        taskContent: '',
        taskSource: '苏州市市场监督管理局',
        taskTitle: '',
        areaList: [],
        area: [],
        unitModuleTaskAreaSaveRequestList: [],
        unitModuleTaskFileSaveRequestList: [],
        unitModuleTaskFormatSaveRequestList: [],
        bodyIndustryList: [],
        bodyIndustry: [],
        unitNumber: 0,
      },
      bodyIndustryAll: false,
      areaAll: false,
      rules: {
        taskTitle: [
          { required: true, message: '请输入任务名称', trigger: 'blur' },
        ],
        bodyIndustry: [
          {
            type: 'array',
            required: true,
            message: '请至少选择一个单位业态',
            trigger: 'blur',
          },
        ],
        area: [
          {
            type: 'array',
            required: true,
            message: '请至少选择一个区域',
            trigger: 'blur',
          },
        ],
        completionDeadline: [
          {
            required: true,
            message: '请选择完成截止时间',
            trigger: 'blur',
          },
        ],
        taskContent: [
          {
            required: true,
            message: '请输入任务内容',
            trigger: 'blur',
          },
        ],
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() <= Date.now()-60*60*1000*24;
        },
      },
    };
  },
  methods: {
    onEditorChange(e) {
      // console.log(e);
      this.query.taskContent = e.html;
    },
    findListNoParentByParentCode() {
      this.$http
        .findListNoParentByParentCode({})
        .then(res => {
          if (res.code == 200) {
            this.query.areaList = res.data;
            // this.onCheckbox(true);
            // this.areaAll = true;
            if (this.query.area.length == this.query.areaList.length) {
              this.areaAll = true;
            }
          } else {
            this.$error(res.msg);
          }
        })
        .catch(err => {
          this.$error();
          console.log(err);
        });
    },
    onCheckbox(e) {
      if (e) {
        this.query.area = this.query.areaList.map(x => x.areaName);
      } else {
        this.query.area = [];
      }
    },
    onCheckboxBodyIndustry(e) {
      if (e) {
        this.query.bodyIndustry = this.query.bodyIndustryList.map(
          x => x.bodyIndustryRemarks
        );
      } else {
        this.query.bodyIndustry = [];
      }
    },
    onCheckboxGroup(e) {
      if (e.length == this.query.areaList.length) {
        this.areaAll = true;
      } else {
        this.areaAll = false;
      }
    },
    onCheckboxGroupBodyIndustry(e) {
      if (e.length == this.query.bodyIndustryList.length) {
        this.bodyIndustryAll = true;
      } else {
        this.bodyIndustryAll = false;
      }
    },
    success(e) {
      if (e.code == 200) {
        this.query.unitModuleTaskFileSaveRequestList.push({
          name: this.$imageName,
          fileName: this.$imageName,
          fileUrl: this.$uploadURL + e.data,
          url: this.$uploadURL + e.data,
        });
      }
    },
    onError() {
      this.$error('上传失败');
    },
    onRemove(e) {
      this.query.unitModuleTaskFileSaveRequestList = this.query.unitModuleTaskFileSaveRequestList.filter(
        x => x.uid != e.uid
      );
    },
    beforeRemove(file) {
      if (file && file.status === 'success') {
        return this.$confirm('确定删除这个文件吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        });
      }
    },
    submit(type) {
      this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          this.query.releaseStatus = type;
          this.query.unitModuleTaskAreaSaveRequestList = [];
          this.query.unitModuleTaskFormatSaveRequestList = [];
          this.query.areaList.forEach(x => {
            if (this.query.area.includes(x.areaName)) {
              this.query.unitModuleTaskAreaSaveRequestList.push({
                areaCode: x.areaCode,
                areaName: x.areaName,
              });
            }
          });
          this.query.bodyIndustryList.forEach(x => {
            if (this.query.bodyIndustry.includes(x.bodyIndustryRemarks)) {
              this.query.unitModuleTaskFormatSaveRequestList.push({
                bodyIndustry: x.bodyIndustry,
                bodyIndustryRemarks: x.bodyIndustryRemarks,
                isSpecialFood: x.isSpecialFood,
              });
            }
          });
          this.$http
            .saveUnitModuleTask(this.query)
            .then(res => {
              if (res.code == 200) {
                this.$success('保存成功');
                this.$router.push('/task');
              } else {
                this.$error(res.msg);
              }
            })
            .catch(err => {
              console.log(err);
              this.$error();
            });
        } else {
          this.$error('请输入必填项');
        }
      });
    },
    getModulesCate() {
      this.$http
        .getModulesCate({
          isPage: 1,
          isOpen: 1,
          searchValue: '餐饮服务经营者',
          //           isSpecialFood: this.$route.query.isSpecialFood,
          isSpecialFood: 0,
        })
        .then(res => {
          if (res.code == 200) {
            this.query.bodyIndustryList = res.data;
            // this.onCheckboxBodyIndustry(true);
            // this.bodyIndustryAll = true;
            // query.bodyIndustry
            if (
              this.query.bodyIndustry.length ==
              this.query.bodyIndustryList.length
            ) {
              this.bodyIndustryAll = true;
            }
          } else {
            this.$error(res.msg);
          }
        })
        .catch(err => {
          this.$error();
          console.log(err);
        });
    },
  },
  // 监听属性
  watch: {},
  //实例销毁之前
  beforeDestroy() {
    sessionStorage.removeItem('viewTask');
  },
};
// query.area
</script>
<style lang="less" scoped>
.container {
  padding: 20px;
  .checkbox {
    display: flex;
    .checkbox_last {
      margin-right: 15px;
    }
  }
  .form_button {
    text-align: right;
  }
}
</style>
